$package("common.tools.scheduledTask");
$import("common.tools.scheduledTask.scheduledTask")
$import('itsm.itsop.selectCompany');
if(isCIHave){
	$import("itsm.cim.configureItemUtil");
}
$import("common.config.dictionary.dataDictionaryUtil");
$import("common.config.category.eventCategoryTree");
$import("common.security.userUtil");
$import("common.eav.attributes");
$import("common.tools.schedule.setMonthly");
$import("common.knowledge.knowledgeTree");
$import('common.config.category.serviceCatalog');
$import('common.config.formCustom.formControl');
$import('itsm.request.requestCommon');
$import('common.eav.attributes');
/**
 * @author QXY
 * @constructor users
 * @description 定期任务编辑
 * @date 2011-10-11
 * @since version 1.0
 */
common.tools.scheduledTask.editScheduledTaskFormCustom=function(){
	this.rowHTML='<tr id="ref_ci_CIID">'+
	'<td align="center">CINO</td>'+
	'<td align="center"><input type="hidden" name="cinos" value="CIID" />'+
	'<a href=javascript:common.tools.scheduledTask.editScheduledTaskFormCustom.lookConfigureItemInfo(CIID)>CINAME</a>'+
	'</td>'+
	'<td align="center">CATEGORYNAME</td>'+
	'<td align="center">CISTATUS</td>'+
	'<td align="center"><a onclick=itsm.cim.configureItemUtil.removeRow("#ref_ci_CIID")>DELETE</a></td>'+
	'</tr>';
	var edit_requestScheduledTask_attrJson = "";
	return {
		/**
		 * @description 格式化值
		 */
		inputSetValue:function(value){
			if(value==null || value=='null')
				return '';
			else
				return value;
		},
		/**
		 * @description 选择请求分类
		 * @param showAttrId 显示div的id
		 * @param dtoName 
		 */
		selectEditRequestCategory:function(showAttrId,dtoName){
			common.config.category.eventCategoryTree.showSelectTree('#request_category_select_window'
					,'#request_category_select_tree'
					,'Request'
					,'#edit_scheduledTask_categoryName'
					,'#edit_scheduledTask_categoryNo'
					,''
					,'',showAttrId,dtoName);
			
		},
		
		setEditScheduledTaskRequestCss:function(res){
			itsm.request.requestCommon.bindAutoCompleteToRequest('editScheduledTaskRequest_formField');
			$("#editScheduledTaskRequest_formField :input[attrType=Lob]").parent().attr("class","field_lob");
			$.each($("#editScheduledTaskRequest_formField :input[attrType=Lob]"),function(ind,val){
				$(val).parent().parent().attr("class","field_options_lob field_options");
			});
			$("#editScheduledTaskRequest_formField").find("div[class=field_options] div[class=label]:odd").css("border-left","none");
			itsm.request.requestCommon.showFormBorder(res.isShowBorder,"#editScheduledTaskRequest_formField","#editRequestFormCustom_is_scheduled","#editRequestFormCustom_no_scheduled");
			if(res.isNewForm){
				$("#editRequestScheduledTask_isNewForm").val(true);
			}else{
				$("#editRequestScheduledTask_isNewForm").val(false);
			}
			common.tools.scheduledTask.editScheduledTaskFormCustom.oneRowCss(res);
		},
		/**
		 * 根据ID查询定期任务
		 * @param 定期任务id
		 */
		findScheduledTaskById:function(id){
			var _url = 'scheduledTask!findScheduledTaskById.action';
			$.post(_url,'queryDTO.scheduledTaskId='+id,function(data){
				if(data!=null){
					var res = data.requestDTO;
					$('#edit_scheduledTask_requestServiceDirNos').val(res.requestServiceDirNos);
					$('#editRequestScheduledTask_formId').val(res.formId);
					$('#editRequestScheduledTask_eavId').val(res.eavId);
					$('#scheduledTaskType').val(data.scheduledTaskType);
					if(res.formId){
						var _param = {"formCustomId" : res.formId};
						$.post('formCustom!findFormCustomById.action',_param,function(formData){
							var formCustomContents = common.config.formCustom.formControlImpl.editHtml(formData.formCustomContents,'editScheduledTaskRequest_formField');
							$('#editScheduledTaskRequest_formField').html(formCustomContents);
							$('#editScheduledTaskRequest_formField').prepend($('#editScheduledTask_codeAndServices').html());
							itsm.request.requestCommon.setRequestFormValuesByScheduledTask(res,'#editScheduledTaskRequest_formField',res.attrVals,formData.eavNo);
							$('#editScheduledTaskRequest_formField #request_edesc').attr("id","edit_scheduledTask_edesc");//将编辑器的id改为editrequest_edesc
							$.parser.parse($('#editScheduledTaskRequest_formField'));
							
							common.config.formCustom.formControlImpl.formCustomInit('#editScheduledTaskRequest_formField');
							common.config.formCustom.formControlImpl.formCustomInitByDataDictionaray('#editScheduledTaskRequest_formField');
							common.tools.scheduledTask.editScheduledTaskFormCustom.setEditScheduledTaskRequestCss(res);
							$("#editScheduledTaskRequest_formField #editScheduledTaskField_requestServiceDirs").val(res.serviceDirNames);
							endProcess();
						});
					}else{
						$("#editScheduledTaskRequest_formField").load('common/config/formCustom/defaultField.jsp',function(){
							itsm.request.requestCommon.initDefaultFormByAttr('editScheduledTaskRequest_formField');
							$('#editScheduledTaskRequest_formField').prepend($('#editScheduledTask_codeAndServices').html());
							itsm.request.requestCommon.setRequestParamValueToOldForm('#editScheduledTaskRequest_formField',res);
							itsm.request.requestCommon.setRequestParamValueToOldFormByDataDictionaray('#editScheduledTaskRequest_formField',res);
							$("#editScheduledTaskRequest_formField #editScheduledTaskField_requestServiceDirs").val(res.serviceDirNames);
							common.tools.scheduledTask.editScheduledTaskFormCustom.setEditScheduledTaskRequestCss(res);
							$('#editScheduledTaskRequest_formField #request_edesc').attr("id","edit_scheduledTask_edesc");//将编辑器的id改为editrequest_edesc
							itsm.request.requestCommon.setfieldOptionsLobCss("#editScheduledTaskRequest_formField");
							if(!res.isNewForm){
								common.eav.attributes.findAttributeByScheduledTask(res.attrVals,res.ecategoryNo,'itsm.request','requestDTO',function(json){
									if(jsonStr!=undefined){
										var jsonStr=common.security.base64Util.encode(JSON.stringify(json));
										$("#editScheduledTaskRequest_formField").append(common.config.formCustom.formControlImpl.editHtml(jsonStr,'editScheduledTaskRequest_formField'));
									}
									common.config.formCustom.formControlImpl.formCustomInit('#editScheduledTaskRequest_formField');
									itsm.request.requestCommon.setRequestParamValueToOldFormByDataDictionaray('#editScheduledTaskRequest_formField',res);
									endProcess();
								});
							}else{
								common.config.formCustom.formControlImpl.formCustomInit('#editScheduledTaskRequest_formField');
								endProcess();
							}
						});
					}
					
					
					// 配置项
					if(data.requestDTO.relatedConfigureItemNos!=null){
						var ids =data.requestDTO.relatedConfigureItemNos;
						var param = $.param({"ids":ids},true);
						$.post("ci!findByIds.action",param,function(ci){
							if(ci!=null){
								var cigDTO=ci;
								for(var i=0;i<cigDTO.length;i++){
									var status='';
									if(cigDTO[i].status!=null)
										status=cigDTO[i].status;
									var newRowHTML=rowHTML.replace(/CIID/g,cigDTO[i].ciId)
									.replace(/CINO/g,cigDTO[i].cino)
									.replace(/CIDETAIL_TITLE/g,i18n['ci_configureItemInfo'])
									.replace(/CINAME/g,cigDTO[i].ciname)
									.replace(/CATEGORYNAME/g,cigDTO[i].categoryName)
									.replace(/CISTATUS/g,status)
									.replace(/DELETE/g,i18n['deletes']); 
									$(newRowHTML).appendTo('#scheduledTask_edit_relatedCIShow tbody');
								}
							}
						});
					}
					// 所属服务
					if(data.requestDTO.requestServiceDirNo!=null){
						var ids =data.requestDTO.requestServiceDirNoStrs;
						var param="";
						if(ids == null || ids == ''){
							var idsNo=data.requestDTO.requestServiceDirNo;
							if(idsNo != null && idsNo != 0){
								param = $.param({"categoryNos":data.requestDTO.requestServiceDirNo},true);
							}
						}else{
							var ids1 = ids.split(",");
							param = $.param({"categoryNos":ids1},true);
						}
						if(param!=""){
							$.post("event!findScheduledCategoryArray.action",param,function(res){
								if(res != null){
									for ( var i = 0; i < res.length; i++) {
										$("<tr id=edit_scheduledTask_"+res[i].eventId+"><td>"+res[i].eventName+"</td><td>"+res[i].scores+"</td><td><a onclick=common.knowledge.knowledgeTree.serviceRm("+res[i].eventId+")>"+i18n['deletes']+"</a><input type=hidden name=serviceDirNos value="+res[i].eventId+"></td></tr>").appendTo('#edit_scheduledTask_serviceDirectory_tbody');
									}
								}
							});
						}
					}
					/*
					 * $('#edit_scheduledTask_ref_requestServiceDirNo').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.requestDTO.requestServiceDirNo));
					 * $('#edit_scheduledTask_ref_requestServiceDirName').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.requestDTO.requestServiceDirName));
					 */
					// 时间表
					$('#edit_scheduledTask_startDate_input').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(timeFormatterOnlyData(data.taskDate)));
					$('#edit_scheduledTask_endDate_input').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(timeFormatterOnlyData(data.taskEndDate)));
					if(data.timeType=='day'){// 日计划
						$('#timeType_day').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('day','edit_')
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskMinute));
					}
					if(data.timeType=='weekly'){// 周计划
						common.tools.scheduledTask.scheduledTask.everyWhatChange('weekly','edit_')
						$('#timeType_weekly').attr('checked',true);
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskMinute));
						var weekWeeks=data.weekWeeks;
						
						if(weekWeeks!=null && weekWeeks!=''){
							var weekWeekArray=weekWeeks.split(',');
							for(var i=0;i<weekWeekArray.length;i++){
								$('#request_checkbox_'+trim(weekWeekArray[i])).attr('checked',true);
							}
						}
						
					}
					
					if(data.timeType=='month'){// 月计划
						
						$('#timeType_month').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('month','edit_')
						$('#edit_scheduledTask_monthDay').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.monthDay));
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskMinute));
						
						var monthMonths=data.monthMonths;
						common.tools.schedule.setMonthly.setmonthDayForEdit('edit_scheduledTask_monthDay',monthMonths);
						$('#edit_scheduledTask_monthDay').val(data.monthDay+" ");
						if(monthMonths!=null && monthMonths!=''){
							var monthMonths=monthMonths.split(',');
							for(var i=0;i<monthMonths.length;i++){
								$('#request_checkbox_'+trim(monthMonths[i])).attr('checked',true);
							}
						}
					}
					if(data.timeType=='cycle'){// 周期性计划
						$('#timeType_cycle').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('cycle','edit_')
						$('#edit_scheduledTask_cyclicalDay').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.cyclicalDay));
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskMinute));
					}
					if(data.timeType=='cycleMinute'){// 周期性计划(分钟)
						$('#timeType_cycleMinute').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('cycleMinute','edit_')
						$('#edit_scheduledTask_cyclicalMinute').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.cyclicalMinute));
						$('#edit_scheduledTask_cyclicalDay').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.cyclicalDay));
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskMinute));
					}
					if(data.timeType=='on_off'){// 一次性计划
						$('#timeType_on_off').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('on_off','edit_')
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTaskFormCustom.inputSetValue(data.taskMinute));
					}
					
					// 附件
					if(data.requestDTO.attachmentStr!=null){
						$('#edit_scheduledTask_attachmentStr').val(data.requestDTO.attachmentStr);
						var str="<div id='{id}'><a>{attachmentName}</a><a href=javascript:deleteFile('{attachmentStr}','#edit_scheduledTask_success_attachment','#edit_scheduledTask_attachmentStr')>&nbsp;&nbsp;"+i18n['deletes']+"</a></div>";
						var attachmentStr=data.requestDTO.attachmentStr;
						if(attachmentStr.indexOf('-s-')!=-1){
							var attrArr=attachmentStr.split('-s-');
							for(var i=0;i<attrArr.length;i++){
								var url=attrArr[i].replace("\\","/");
			        			if(url!=null && url!=''){
			            			var attrArrs=url.split("==");
			            			var strid=attrArrs[1].substring(attrArrs[1].indexOf("/")+1,attrArrs[1].indexOf("."))
			            			$('#edit_scheduledTask_success_attachment').append(str.replace('{id}',strid).replace('{attachmentName}',attrArrs[0]).replace('{attachmentStr}',attrArrs[1]));
			            			// deleteFile('20111018/1318927080403.txt','#edit_scheduledTask_success_attachment','#edit_scheduledTask_attachmentStr')
			        			}
							}
						}
					}

				}
			})
		},
		/**
		 * 打开配置项详情
		 * @param 配置项id
		 */
		lookConfigureItemInfo:function(ciId){
			basics.tab.tabUtils.reOpenTab("ci!findByciId.action?ciEditId="+ciId,i18n['ci_configureItemInfo'])
		},
		
		/**
		 * 保存定期任务
		 */
		editScheduledTask:function(){
			if($('#editScheduledTimeSettings form').form('validate')){
				if($('#editScheduledTaskForm').form('validate')){
					if($("#editScheduledTimeSettings input[name='scheduledTaskDTO.timeType']:checked").val() == "month" && $("#edit_scheduledTask_monthDay").val()==null){
						msgAlert(i18n.scheduledTask_monthPlan_monthDayIsNotNull,'info');
					}else{
						var myDate=new Date() 
			    		var month=myDate.getMonth()+1;
						if(!DateComparison($('#edit_scheduledTask_endDate_input').val(),myDate.getFullYear()+'-'+month+'-'+(myDate.getDate()-1))){
							var _edesc="";
							if(CKEDITOR.instances['edit_scheduledTask_edesc']){
								var oEditor = CKEDITOR.instances.edit_scheduledTask_edesc;
								_edesc = oEditor.getData();
							}
							var bool=trim(_edesc)==''?false:true;
							if(!bool){
								msgAlert(i18n['titleAndContentCannotBeNull'],'info');
							}else{
								$('#edit_scheduledTask_edesc').val(_edesc);
								itsm.cim.ciCategoryTree.getFormAttributesValue("#editScheduledTaskForm");
								var frm = $('#editScheduledTask_layout form').serialize();
								var _url = 'scheduledTask!editScheduledTask.action';
								// 调用
								startProcess();
								$.post(_url,frm,function(res){
										endProcess();
										basics.tab.tabUtils.closeTab(i18n['title_edit_scheuledTask']);
										
										basics.tab.tabUtils.addTab(i18n['title_scheduled_task_manage'],'../pages/common/tools/scheduledTask/scheduledTasksManage.jsp');
										$('#scheduledTasksGrid').trigger('reloadGrid');
										msgShow(i18n['msg_edit_successful'],'show');
									
								});
							}
						}else{
							msgAlert(i18n['tip_endTime_cannot_be_before_startTime'],'info');
							$('#editScheduledTask_tab').tabs('select', '*'+i18n.scheduledTask_time_setting);
						}
					}
				}
			}else{
				$('#editScheduledTask_tab').tabs('select', '*'+i18n.scheduledTask_time_setting);
			}
		},
		
		/**
		 * @description 选择请求分类.
		 */
		selectRequestCategory:function(){

			common.config.category.eventCategoryTree.showSelectTree('#request_category_select_window'
					,'#request_category_select_tree'
					,'Request'
					,'#edit_scheduledTask_categoryName'
					,'#edit_scheduledTask_categoryNo');
			
		},
		/**
		 * @description 点击tab后，根据tab标题加载不同的数据
		 * @param title 标题
		 */
		tabClickEvents:function(title){
			if(title==i18n["config_extendedInfo"]){// 扩展属性
				(eno,'itsm.request',res.categoryEavId,'scheduledTask_edit_eavAttributet','request')
				common.eav.attributes.findAttributeByEno(scheduledTaskId,'request','scheduledTask_edit_eavAttributet');// 加载
			}
		},
		oneRowCss:function(res){
			if(res.isShowBorder=="1"){
				var leng = $("#editScheduledTaskRequest_formField").find("div[class='field_options_2Column field_options']").length;
				if(leng>0){
					$.each($("#editScheduledTaskRequest_formField").find("div[class='field_options']"),function(ind,obj){
						if(ind==0){
							$(obj).attr("class","field_options_2Column field_options");
							$(obj).find("div[class='field']").attr("class","field_lob");
						}else{
							$(obj).remove();
						}
					});
					$.each($("#editScheduledTaskRequest_formField").find("div[class='field_options_lob field_options']"),function(ind,obj){
						$(obj).children(":first").css("height","292px");
					});
					$.each($("div[class='field_options_2Column field_options']"),function(ind,obj){
						$(obj).find("div[class='field_lob']").css("margin-top","10px");
					});
					
					$.each($("#editScheduledTaskRequest_formField").find("div[class='field_options_lob field_options']"),function(ind,obj){
						$(obj).find("div[class='field_lob']").css("margin-left","25px");
					});
					
				}
			}else{
				var leng = $("#editScheduledTaskRequest_formField").find("div[class='field_options_2Column field_options']").length;
				if(leng>0){
					$.each($("#editScheduledTaskRequest_formField").find("div[class='field_options']"),function(ind,obj){
						if(ind==0){
							$(obj).attr("class","field_options_2Column field_options");
							$(obj).find("div[class='field']").attr("class","field_lob");
						}else{
							$(obj).remove();
						}
					});
					//$("#editScheduledTaskField_requestServiceDirs").parent().attr("class","field_lob").parent().attr("class","field_options_2Column field_options");
					$.each($("div[class='field_options_2Column field_options']"),function(ind,obj){
						$(obj).find("div[class='field_lob'] :input").css("margin-top","0px");
					});
					
					$.each($("#editScheduledTaskRequest_formField").find("div[class='field_options_lob field_options']"),function(ind,obj){
						$(obj).find("div[class='field_lob']").css("margin-left","20px");
					});
				}
			}
		},
		/**
		 * @description 初始化
		 */
		init:function(){
			// 绑定日期控件
			DatePicker97(['#edit_scheduledTask_startDate_input','#edit_scheduledTask_endDate_input']);
			$("#editScheduledTask_loading").hide();
			$("#editScheduledTask_layout").show();
			// 设定月份总天数
			common.tools.schedule.setMonthly.setmonthDay('edit_everyWhat_monthly','edit_scheduledTask_monthDay');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('effectRange','#edit_scheduledTask_effectRange');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('seriousness','#edit_scheduledTask_seriousness');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('imode','#edit_scheduledTask_imode');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('level','#edit_scheduledTask_level');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('priority','#edit_scheduledTask_priority');
			
			setTimeout(function(){
				getUploader('#edit_scheduledTask_file','#edit_scheduledTask_attachmentStr','#edit_scheduledTask_success_attachment','');
			},0)
		
			$('#edit_scheduledTask_companyName').click(function(){// 选择公司
				itsm.itsop.selectCompany.openSelectCompanyWin('#edit_scheduledTask_companyNo','#edit_scheduledTask_companyName','#edit_scheduledTask_createdName,#edit_scheduledTask_createdNo');
			});
			// $('#edit_scheduledTask_categoryName').click(common.tools.scheduledTask.editScheduledTaskFormCustom.selectRequestCategory);
			
			$('#edit_scheduledTask_createdName').click(function(){
				common.security.userUtil.selectUser('#edit_scheduledTask_createdName','#edit_scheduledTask_createdNo','','loginName',$('#edit_scheduledTask_companyNo').val());
			})
			
			// 绑定选择配置项
			$('#edit_scheduledTask__ref_ci_btn').click(function(){
				itsm.cim.configureItemUtil.requestSelectCI('#scheduledTask_edit_relatedCIShow',$('#edit_scheduledTask_companyNo').val(),'');
			});
			
			$('#editScheduledTaskBtn').click(common.tools.scheduledTask.editScheduledTaskFormCustom.editScheduledTask);// 保存定期任务
			
			$('#edit_scheduledTask_backList').click(function(){
				basics.tab.tabUtils.addTab(i18n['title_scheduled_task_manage'],'../pages/common/tools/scheduledTask/scheduledTasksManage.jsp');
			});// 返回列表
			
			
			$('#edit_scheduledTask_service_add').click(function(){
				common.config.category.serviceCatalog.selectServiceDir('#edit_scheduledTask_serviceDirectory_tbody');
			});
			
		}
	}
}();
$(document).ready(common.tools.scheduledTask.editScheduledTaskFormCustom.init);